package cn.bluech.example.ui;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import cn.bluech.example.R;

/**
 * Description:
 * Create by Codeant on 2019/4/16.
 */
public class WifiConnectActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private final static String WIFI_SSID = "TP-LINK_ACA6";
    private Button mBtnOpenWifi;
    private Button mBtnCloseWifi;
    private Button mBtnAddWifi;
    private Button mBtnDelWifi;
    private Button mBtnConnect;
    private Button mBtnDisConnect;
    private TextView mTextViewShowResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_connect);

        initUi();
    }

    private void initUi() {
        mBtnOpenWifi = (Button) findViewById(R.id.btnOpenWifi);
        mBtnOpenWifi.setOnClickListener(this);
        mBtnCloseWifi = (Button) findViewById(R.id.btnCloseWifi);
        mBtnCloseWifi.setOnClickListener(this);
        mBtnAddWifi = (Button) findViewById(R.id.btnAddWifi);
        mBtnAddWifi.setOnClickListener(this);
        mBtnDelWifi = (Button) findViewById(R.id.btnDelWifi) ;
        mBtnDelWifi.setOnClickListener(this);
        mBtnConnect = (Button) findViewById(R.id.btnConnect);
        mBtnConnect.setOnClickListener(this);
        mBtnDisConnect = (Button) findViewById(R.id.btnDisConnect);
        mBtnDisConnect.setOnClickListener(this);
        mTextViewShowResult = (TextView) findViewById(R.id.textViewShowResult);
    }

    @Override
    public void onClick(View view) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mTextViewShowResult.setText("");
        // "TP-LINK_ACA6"
        switch (view.getId()) {
            case R.id.btnOpenWifi:
                if (openWifi()) {
                    mTextViewShowResult.setText("正在打开 Wifi,请稍等");
                } else {
                    mTextViewShowResult.setText("打开 Wifi 失败,Wifi 已经开启?");
                }
                break;
            case R.id.btnCloseWifi:
                if (closeWifi()) {
                    mTextViewShowResult.setText("正在关闭 Wifi,请稍等");
                } else {
                    mTextViewShowResult.setText("关闭 Wifi 失败,Wifi 已经关闭?");
                }
                break;
            case R.id.btnAddWifi:
                int networkId = addWifiItem(WIFI_SSID);
                mTextViewShowResult.setText("得到的 Wifi 的 ID 是:" + networkId);
                break;
            case R.id.btnDelWifi:
                forgetConfiguration(this,createWifiConfiguration(WIFI_SSID));
                break;
            case R.id.btnConnect:
                connectToSpecSsid(addWifiItem(WIFI_SSID));
                break;
            case R.id.btnDisConnect:
                disableSpecSsid(addWifiItem(WIFI_SSID));
                break;
        }
    }

    public static WifiConfiguration createWifiConfiguration(String SSID) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.allowedKeyManagement.clear();
        wifiConfiguration.allowedAuthAlgorithms.clear();
        wifiConfiguration.hiddenSSID = true;

        // 无密码
//        wifiConfiguration.SSID = "\"" + SSID + "\"";
//        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        // wpa
        wifiConfiguration.preSharedKey = "\"huahua123\"";
        wifiConfiguration.hiddenSSID = true;
        wifiConfiguration.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.OPEN);
        wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wifiConfiguration.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.TKIP);
        // wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wifiConfiguration.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.CCMP);
        wifiConfiguration.status = WifiConfiguration.Status.ENABLED;


        return wifiConfiguration;
    }

    private boolean openWifi() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        boolean result = false;
        switch (wifiManager.getWifiState()) {
            case WifiManager.WIFI_STATE_DISABLED:
            case WifiManager.WIFI_STATE_DISABLING:
                wifiManager.setWifiEnabled(true);
                result = true;
                break;
            case WifiManager.WIFI_STATE_ENABLED:
            case WifiManager.WIFI_STATE_ENABLING:
                result = false;
                break;
        }
        return result;
    }

    private boolean closeWifi() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        boolean result = false;
        switch (wifiManager.getWifiState()) {
            case WifiManager.WIFI_STATE_ENABLED:
            case WifiManager.WIFI_STATE_ENABLING:
                wifiManager.setWifiEnabled(false);
                result = true;
                break;
            case WifiManager.WIFI_STATE_DISABLED:
            case WifiManager.WIFI_STATE_DISABLING:
                result = false;
                break;
        }
        return result;
    }

    private int addWifiItem (String ssid) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
        int networkId = -10;
        if (null != wifiConfigurations) {
            for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
                    networkId = wifiConfiguration.networkId;
                    break;
                }
            }
        }

        if (networkId == -10) {
            networkId = wifiManager.addNetwork(createWifiConfiguration(ssid));
        }

        return networkId;
    }

    private boolean delWifiItem (String ssid) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
        boolean result = false;
        int networkId = -10;
        if (null != wifiConfigurations) {
            for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
                    networkId = wifiConfiguration.networkId;
                    Log.i(TAG, "delWifiItem: 找到对应的 ssid,编号为:" + networkId);
                    break;
                }
            }
        }

        if (networkId != -10) {
            Log.i(TAG, "delWifiItem: 执行删除指定网络的过程");
            wifiManager.removeNetwork(networkId);
            result = true;
        }

        wifiConfigurations = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
            if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
                Log.i(TAG, "delWifiItem: 又找到对应的 ssid,编号为:" + networkId);
                result = false;
                break;
            }
        }

        return result;
    }

    private boolean connectToSpecSsid(int netId) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager.enableNetwork(netId,true);
    }

    private boolean disableSpecSsid(int netId) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager.disableNetwork(netId);
    }

    public static void forgetConfiguration(Context context, WifiConfiguration config) {
        if (config == null) {
            return;
        }

        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configuredNetworks = wifiMan.getConfiguredNetworks();
        if (configuredNetworks == null) {
            Log.e(TAG, "failed to get configured networks");
            return;
        }

        for (WifiConfiguration wc : configuredNetworks) {
            if (wc != null && wc.SSID != null && TextUtils.equals(wc.SSID, config.SSID)) {
                wifiMan.removeNetwork(wc.networkId);
                //wifiMan.forget(wc.networkId, null);
                Log.d(TAG, "forgot network config: " + wc.toString());
                break;
            }
        }
    }
}
